<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {Plus, Refresh} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {deleteCartItem, listCartItem, updateCartItemAmount} from '@/api/business/cartItem.js'
import { listAddress } from '@/api/user/address.js'
import { saveSbOrder } from '@/api/business/sbOrder.js'

// 购物车列表数据
const cartItemList = ref([])

const tableRef = ref(null)

// 删除购物车
const handleDelete = async (ids) => {
  try {
    const res = await deleteCartItem(ids)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页只剩要被删除的条数且不是第一页，删除后自动跳转到上一页
      if (cartItemList.value.length === ids.length && pagination.page > 1) {
        pagination.page--
      }
      await getCartItemList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '删除失败')
  }
}

// 处理单个删除 - 二次确认
const handleSingleDelete = (row) => {
  ElMessageBox.confirm(
          '确定要删除购物车 ' + row.id + ' 吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
  )
          .then(() => handleDelete([row.id]))
          .catch(() => {
            console.log('取消删除，不做任何操作')
          })
}

// 计算属性：检查是否有选中的行
const hasSelectedRows = computed(() => {
  return tableRef.value ? tableRef.value.getSelectionRows().length > 0 : false
})

// 处理批量删除 - 二次确认
const handleBatchDelete = async () => {
  const selectedRows = tableRef.value.getSelectionRows()
  if (!selectedRows || selectedRows.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  // 弹出确认对话框
  ElMessageBox.confirm(
          '确定要删除选中的 ' + selectedRows.length + ' 记录吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
  )
          .then(() => handleDelete(selectedRows.map(item => item.id)))
          .catch(() => {
            console.log('取消删除，不做任何操作')
          })
}

const tableLoading = ref(false)

// 获取购物车列表数据
const getCartItemList = async () => {
  tableLoading.value = true
  try {
    const res = await listCartItem({
      ...pagination,
    })
    if (res.code === 200) {
      cartItemList.value = res.data.list
      pagination.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取购物车列表失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '获取购物车列表失败')
  } finally {
    tableLoading.value = false
  }
}

const addressList = ref([])
const selectedAddressId = ref(null)
const remark = ref('')

// 获取收货地址列表
const getAddressList = async () => {
  try {
    const res = await listAddress({ page: 1, size: 100 })
    if (res.code === 200 && Array.isArray(res.data.list)) {
      addressList.value = res.data.list
      if (addressList.value.length > 0) {
        selectedAddressId.value = addressList.value[0].id
      }
    }
  } catch (e) {
    ElMessage.error('获取收货地址失败')
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  getCartItemList()
  getAddressList()
})

// 分页相关数据
const pagination = reactive({
  // 每页显示的数据条数
  size: 100,
  // 当前页码，从1开始
  page: 1,
  // 总数据条数，会在获取数据时更新
  total: 0
})

// 分页变化处理函数
const handleCurrentChange = async (val) => {
  pagination.page = val
  await getCartItemList()
}

const handleSizeChange = async (val) => {
  pagination.size = val
  pagination.page = 1
  await getCartItemList()
}

const handleRefresh = () => {
  getCartItemList()
}

// 商品数量变化时触发
const onAmountChange = async (row, current, old) => {
  let factor = 1;
  if (current < old) {
    factor = -1;
  }

  try {
    const res = await updateCartItemAmount({
      productSkuId: row.productSkuId,
      factor: factor
    })
    if (res.code === 200) {
      ElMessage.success('数量更新成功')
      await getCartItemList()
    } else {
      ElMessage.error(res.msg || '数量更新失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '数量更新失败')
  }
}

const submitOrder = async () => {
  const address = addressList.value.find(item => item.id === selectedAddressId.value)?.fullAddress || '';
  const remarkValue = remark.value;
  const items = cartItemList.value.map(item => ({
    productSkuId: item.productSku?.id,
    amount: item.amount
  }));
  const orderData = {
    address,
    remark: remarkValue,
    items
  };
  try {
    const res = await saveSbOrder(orderData)
    if (res.code === 200) {
      ElMessage.success('下单成功！')
      await getCartItemList()
    } else {
      ElMessage.error(res.msg || '下单失败')
    }
  } catch (e) {
    ElMessage.error(e.response?.data?.msg || '下单失败')
  }
}
</script>

<template>
  <div class="cartItem-container">
    <!-- 顶部按钮 -->
    <div class="top-tools">
      <div class="left">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!hasSelectedRows">批量删除</el-button>
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 购物车列表 -->
    <el-table
      ref="tableRef"
      :data="cartItemList"
      v-loading="tableLoading"
      :table-layout="'auto'"
      style="width: 100%"
      border
    >
      <el-table-column type="selection"></el-table-column>
      
      <!-- 商品信息列 -->
      <el-table-column label="商品信息">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <img
              :src="scope.row.product?.image"
              alt=""
              style="width: 48px; height: 48px; object-fit: cover; border-radius: 6px; margin-right: 10px;"
            />
            <div>
              <div style="font-weight: bold;">{{ scope.row.product?.title }}</div>
              <div style="color: #888; font-size: 13px;">{{ scope.row.productSku?.title }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="单价" prop="productSku.price">
        <template #default="scope">
          <span style="color: #d33; font-weight: bold;">￥{{ scope.row.productSku?.price }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="amount" label="商品数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.amount" :min="1" @change="(current, old) => onAmountChange(scope.row, current, old)" />
        </template>
      </el-table-column>
      
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" link @click="handleSingleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 收货地址和备注 -->
    <div class="order-form-block">
      <el-form label-width="110px">
        <el-form-item label="选择收货地址">
          <el-select v-model="selectedAddressId" placeholder="请选择收货地址" style="width: 400px">
            <el-option v-for="item in addressList" :key="item.id" :label="item.fullAddress || (item.province + item.city + item.district + item.detail + ' ' + item.name + ' ' + item.mobile)" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="remark" type="textarea" style="width: 400px" placeholder="可填写订单备注" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.cartItem-container {
  padding: 20px;
}

.top-tools {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.top-tools .left {
  display: flex;
  gap: 10px;
}

.top-tools .right {
  display: flex;
  align-items: center;
  margin-left: auto;

  .el-form .el-form-item:last-child {
    margin-right: 0;
  }
}

@media screen and (max-width: 768px) {
  .top-tools {
    flex-direction: column;
    align-items: flex-start;
  }

  .top-tools .right {
    margin-left: 0;
    width: 100%;
  }
}

.mb0 {
  margin-bottom: 0;
}

.el-form--inline .el-form-item {
  margin-right: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-form-block {
  margin-top: 32px;
  background: #fff;
  padding: 20px 24px 10px 24px;
  max-width: 700px;
}
</style>
